#include "stdio.h"
#include "string.h"
#include "stdlib.h"

#include "unistd.h"
#include "arpa/inet.h"
#include "sys/socket.h"
#include "pthread.h"

#include "time.h"

#include "config.h"

static char gs_CurTimeBuf[100]={0};
static int gs32_MyTcpSock;
int gem_ConnectSta=0;

pthread_mutex_t mutex_net_sta;

static char TCP_SOCKET_IP_BUF[100]={0};
static char TCP_SOCKET_PORT_BUF[20]={0};

void config_init(int argc,char *argv[])
{
    int spotPoint=0;
    int res = 0;

    if(argc != 0XFF)
    {
        pthread_mutex_init(&mutex_net_sta,NULL); 
    }

    memset(TCP_SOCKET_IP_BUF,0,sizeof(TCP_SOCKET_IP_BUF));
    memset(TCP_SOCKET_PORT_BUF,0,sizeof(TCP_SOCKET_PORT_BUF));

    if(argc == 3 && argv[1]!=NULL && argv[2]!=NULL)
    {
        strcpy(TCP_SOCKET_IP_BUF,argv[1]);
        strcpy(TCP_SOCKET_PORT_BUF,argv[2]);

        for(int i=0;i<strlen(TCP_SOCKET_IP_BUF);i++)//check if ip is ok
        {
            if(TCP_SOCKET_IP_BUF[i] == '.')
            {
                spotPoint++;
            }
            else if(TCP_SOCKET_IP_BUF[i] > '9' || TCP_SOCKET_IP_BUF[i] < '0')
            {
                spotPoint = 0XFF;
                break;
            }
        }

        if(spotPoint != 3)
        {
            res = 1;
        }

        spotPoint = 0;
        for(int i=0;i<strlen(TCP_SOCKET_PORT_BUF);i++)//check if port is ok
        {
            if(TCP_SOCKET_PORT_BUF[i] > '9' || TCP_SOCKET_PORT_BUF[i] < '0')
            {
                spotPoint = 0XFF;
                break;
            }
        }
        
        if(spotPoint == 0XFF || res == 1)//校验不通过,使用默认ip和port
        {
            strcpy(TCP_SOCKET_IP_BUF,SOCKET_IP_DEFAULT);
            strcpy(TCP_SOCKET_PORT_BUF,SOCKET_PORT_DEFAULT);
        }
    }
    else
    {
        strcpy(TCP_SOCKET_IP_BUF,SOCKET_IP_DEFAULT);
        strcpy(TCP_SOCKET_PORT_BUF,SOCKET_PORT_DEFAULT);
    }

    printf("config_init(): cur ip is %s,get socket is %s\n",TCP_SOCKET_IP_BUF,TCP_SOCKET_PORT_BUF);
}

void config_set_connect_sta(EM_NETSTA sta)
{
    pthread_mutex_lock(&mutex_net_sta);
    gem_ConnectSta = sta;
    pthread_mutex_unlock(&mutex_net_sta);
}

EM_NETSTA config_get_connect_sta()
{
    EM_NETSTA sta = NETSTA_NONE;
    pthread_mutex_lock(&mutex_net_sta);
    sta = gem_ConnectSta;
    pthread_mutex_unlock(&mutex_net_sta);
    return sta;
}

void config_error_handling(char *message)
{
    fputs(message,stderr);
    fputc('\n',stderr);
    exit(1);
}

void config_printf_hex(char *message,int len)
{
    for(int i=0;i<len;i++)
    {
        printf("%x ",message[i]);
    }

    printf("\n");
}


char* config_get_cur_time()
{
	time_t timer;//time_t就是long int 类型
	struct tm *tblock;
	timer = time(NULL);
	tblock = localtime(&timer);

	char * time =  asctime(tblock);
	//printf("Local time is1: %s",time);
	memset(gs_CurTimeBuf,0,sizeof(gs_CurTimeBuf));
	memcpy(gs_CurTimeBuf,time,strlen(time));
	//printf("Local time is: %s",gs_CurTimeBuf);

	return gs_CurTimeBuf;
}                

int config_get_cur_socket()
{
    if(config_get_connect_sta() == NETSTA_NONE)
    {
        return -1;
    }

    return gs32_MyTcpSock;
}

int config_tcp_socket_connect()
{
    struct sockaddr_in serv_addr;

    gs32_MyTcpSock=socket(PF_INET,SOCK_STREAM,0);
    if(gs32_MyTcpSock == -1)
    {
        config_error_handling("socket() error");
    }

    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family=AF_INET;
    serv_addr.sin_addr.s_addr=inet_addr(TCP_SOCKET_IP_BUF);
    serv_addr.sin_port=htons((atoi(TCP_SOCKET_PORT_BUF)));

    if(connect(gs32_MyTcpSock,(struct sockaddr*)&serv_addr,sizeof(serv_addr))==-1)//与服务器建立TCP/IP层的socket连接
    {
        printf("config_tcp_socket_connect():connetc failed\n");
        config_set_connect_sta(NETSTA_NONE);
        return -1;
    }
    else
    {
        printf("config_tcp_socket_connect():connect ip %s,port %s succses\n",SOCKET_IP_DEFAULT,SOCKET_PORT_DEFAULT);
        config_set_connect_sta(NETSTA_CONN_SOCKET);
        return gs32_MyTcpSock;
    }
}

int config_tcp_socket_disconnect(int socket)
{
    if(socket == -1)
    {
        printf("config_mqtt_read():invalid socket\n");
        return -1;
    }
    close(socket);
}

int config_mqtt_read(int sockfd,char *packet,int packet_length)
{
    if(sockfd == -1)
    {
        printf("config_mqtt_read():invalid socket\n");
        return -1;
    }

    return (read(sockfd,packet,packet_length));//该函数会阻塞线程
}

int config_mqtt_write(int sockfd,char *packet,int packet_length)
{
    if(sockfd == -1)
    {
        printf("config_mqtt_write():invalid socket\n");
        return -1;
    }

    return(write(sockfd,packet,packet_length));
}
